﻿using System;
using HNAC.Weixin.MP.Context;
using HNAC.Weixin.MP.Entities;
using HNAC.Weixin.MP.MessageHandlers;
using System.Data;
using System.Collections.Generic;
using System.Threading;
using System.IO;
using HNAC.Weixin.MP.AdvancedAPIs;
using Common;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;
using Deepleo.Weixin.SDK;
using Maticsoft.Common;

namespace HNAC.Weixin.CommonService.CustomMessageHandler
{
    /// <summary>
    /// 自定义MessageHandler
    /// </summary>
    public partial class CustomMessageHandler : MessageHandler<MessageContext>
    {
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            try
            {
                var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
                switch (requestMessage.EventKey)
                {
                    case "V1001_createqr":
                        {
                            responseMessage.Content = "您好,正在为您生成专属积分卡片,大约需要等待8秒,请稍等片刻！建议直接通过微信群发助手把生成的积分卡片发出去，这样是最快提升积分的方法";
                            Maticsoft.BLL.tb_userdata buser = new Maticsoft.BLL.tb_userdata();
                            List<Maticsoft.Model.tb_userdata> users = buser.GetModelList(" wxid = '" + requestMessage.FromUserName + "' ");
                            if (users == null || users.Count == 0)
                            {
                                AddUser(requestMessage.FromUserName);
                            }
                            CreateQr(requestMessage.FromUserName, true);
                        }
                        break;
                }
                return responseMessage;
            }
            catch (System.Exception ex)
            {
                AppCommon.Instance.LoggerHandler.Log(ex.Message);
                AppCommon.Instance.LoggerHandler.Log(ex.StackTrace);
            }
            return null;
        }

        public override IResponseMessageBase OnEvent_EnterRequest(RequestMessageEvent_Enter requestMessage)
        {
            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            responseMessage.Content = "您刚才发送了ENTER事件请求。";
            return responseMessage;
        }

        public override IResponseMessageBase OnEvent_LocationRequest(RequestMessageEvent_Location requestMessage)
        {
            throw new Exception("暂不可用");
        }

        /// <summary>
        /// 订阅（关注）事件
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            
            #region
            //获取HNAC.Weixin.MP.dll版本信息
//            var fileVersionInfo = FileVersionInfo.GetVersionInfo(HttpContext.Current.Server.MapPath("~/bin/HNAC.Weixin.MP.dll"));
//            var version = string.Format("{0}.{1}", fileVersionInfo.FileMajorPart, fileVersionInfo.FileMinorPart);
//            responseMessage.Content = string.Format(
//@"欢迎关注【HNAC.Weixin.MP 微信公众平台SDK】，当前运行版本：v{0}。
//您可以发送【文字】【位置】【图片】【语音】等不同类型的信息，查看不同格式的回复。
//
//SDK官方地址：http://weixin.senparc.com
//源代码及Demo下载地址：https://github.com/JeffreySu/WeiXinMPSDK",
            //                version);
            #endregion
            //加入缓存表
            //AppCommon.Instance.Caches[requestMessage.FromUserName] = new UserCacheData();
            
            #region
            //UserCacheData cacheUser = new UserCacheData();
            //ServerCache.SetCache(requestMessage.FromUserName, cacheUser);
            //string sqltext = "SELECT * FROM TWxUserBind WHERE wxUser= '" + requestMessage.FromUserName + "'";
            //DbHelperSQL.DBConnStr = GlobalVar.ShareDBConnStr;
            //DataSet ds = DbHelperSQL.Query(sqltext);
            //if (ds.Tables[0].Rows.Count == 1)
            //{
            //    sqltext = "UPDATE TWxUserBind set hzUserid = '' WHERE wxUser = '" + requestMessage.FromUserName + "'";
            //    DbHelperSQL.ExecuteSql(sqltext);
            //}
            //else
            //{
            //    sqltext = "INSERT INTO TWxUserBind (wxUser) values( '" + requestMessage.FromUserName + "')";
            //    DbHelperSQL.ExecuteSql(sqltext);
            //}
            #endregion

            try
            {
                Maticsoft.BLL.tb_userdata buser = new Maticsoft.BLL.tb_userdata();
                List<Maticsoft.Model.tb_userdata> users = buser.GetModelList(" wxid = '" + requestMessage.FromUserName + "' ");
                Maticsoft.Model.tb_userdata muser = null;
                if (users == null || users.Count == 0)
                {
                    //UserInfoJson ou = User.Info(WeixinConfig.TokenHelper.GetToken(true), requestMessage.FromUserName);
                    //muser = new Maticsoft.Model.tb_userdata();
                    //if (ou == null)
                    //{
                    //    muser.realname = "";
                    //    muser.imgurl = Maticsoft.Common.GlobalVar.Instance.AppDataQrDir + "gzh.png";
                    //}
                    //else
                    //{
                    //    muser.realname = ou.nickname;
                    //    muser.imgurl = ou.headimgurl;
                    //}

                    ////首次添加公众号
                    //muser.qrpath = "";
                    //muser.wxid = requestMessage.FromUserName;
                    //muser.jifen = 0;
                    //muser.tj_num = 0;
                    //muser.gz_time = DateTime.Now;
                    //muser.qrmediaid = " ";
                    //muser.qr_expire_date = DateTime.Now.AddDays(-1);
                    //buser.Add(muser);
                    muser = AddUser(requestMessage.FromUserName);
                    if (!string.IsNullOrEmpty(requestMessage.EventKey))
                    {
                        if (requestMessage.EventKey.Length < 8)
                        {
                            responseMessage.Content = " 建议直接通过微信群发助手把生成的积分卡片发出去，这样是最快提升积分的方法。积分可换取车票，话费等等";
                            return responseMessage;
                        }
                        int sceneid = -1;
                        bool ret = int.TryParse(requestMessage.EventKey.Substring(8), out sceneid);
                        if (!ret)
                        {
                            Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(string.Format("sceneid转换失败,eventkey={0}",requestMessage.EventKey));
                            responseMessage.Content = " 建议直接通过微信群发助手把生成的积分卡片发出去，这样是最快提升积分的方法。积分可换取车票，话费等等";
                            return responseMessage;
                        }
                        sceneid = Convert.ToInt32(requestMessage.EventKey.Substring(8));
                        Maticsoft.Model.tb_userdata tuser = buser.GetModel(sceneid);
                        Decimal tjjifen = Convert.ToDecimal(Maticsoft.Common.Utils.GetAppSettingValue("tjjifen"));
                        UpdateFreezeJifen(tuser, tjjifen);
                        if (AddFreezeRecord(tuser.id,muser.id, tjjifen))
                        {
                            Maticsoft.Common.AppCommon.Instance.AddCache(muser.wxid);
                        }
                        ReplayActiveMessageAPI.RepayText(WeixinConfig.TokenHelper.GetToken(), tuser.wxid, string.Format("您推荐的好友:{0}加入我们,获取{1}积分,请再接再厉!", muser.realname, tjjifen));
                    }
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                AppCommon.Instance.LoggerHandler.Log(ex.Message);
                AppCommon.Instance.LoggerHandler.Log(ex.StackTrace);
            }
            responseMessage.Content = " 建议直接通过微信群发助手把生成的积分卡片发出去，这样是最快提升积分的方法。积分可换取车票，话费等等";
            CreateQr(requestMessage.FromUserName);
            return responseMessage;
        }
        private bool UpdateFreezeJifen(Maticsoft.Model.tb_userdata tuser,decimal jifen)
        {
            try
            {
                Maticsoft.BLL.tb_userdata buser = new Maticsoft.BLL.tb_userdata();
                if (tuser != null)
                {
                    tuser.tj_num += 1;
                    tuser.freezejifen += jifen;
                   if (  buser.Update(tuser))
                   {
                       return true;
                   }
                  

                }
            }
            catch (System.Exception ex)
            {
                Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(ex.Message);
                Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(ex.StackTrace);
            }
            return false;
        }

        private Maticsoft.Model.tb_userdata GetUserByOpenId(string openid)
        {
            Maticsoft.BLL.tb_userdata buser = new Maticsoft.BLL.tb_userdata();
            Maticsoft.Model.tb_userdata muser = null;
            try
            {
                DataSet ds = buser.GetList(" wxid='" + openid + "' ");
                if (Maticsoft.Common.Util2.CheckDataSet(ds))
                {
                    DataTable dt = ds.Tables[0];
                    muser = buser.DataTableToList(dt)[0];
                }
            }
            catch (System.Exception ex)
            {
                Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(ex.Message);
                Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(ex.StackTrace);
            }

            return muser;
        }

        private bool AddFreezeRecord(int tjid,int userid,decimal jifen)
        {
            try
            {
                Maticsoft.BLL.tb_freeze bfreeze = new Maticsoft.BLL.tb_freeze();
                Maticsoft.Model.tb_freeze mfreeze = new Maticsoft.Model.tb_freeze();
                mfreeze.tjuer = tjid;
                mfreeze.userid = userid;
                mfreeze.state = 1;
                mfreeze.freezetime = DateTime.Now;
                mfreeze.freezemoney = jifen;

                if (bfreeze.Add(mfreeze))
                {
                    return true;
                }
            }
            catch (System.Exception ex)
            {
                Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(ex.Message);
                Maticsoft.Common.AppCommon.Instance.LoggerHandler.Log(ex.StackTrace);
            }

            return false;
        }
        /// <summary>
        /// 退订
        /// 实际上用户无法收到非订阅账号的消息，所以这里可以随便写。
        /// unsubscribe事件的意义在于及时删除网站应用中已经记录的OpenID绑定，消除冗余数据。并且关注用户流失的情况。
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_UnsubscribeRequest(RequestMessageEvent_Unsubscribe requestMessage)
        {
            //Maticsoft.BLL.userdata buser = new Maticsoft.BLL.userdata();
            //DataSet ds = buser.GetList(" wxid='" + requestMessage.FromUserName + "'");

            //if (Maticsoft.Common.Util.CheckDataSet(ds))
            //{
            //    List<Maticsoft.Model.userdata> musers = buser.DataTableToList(ds.Tables[0]);
            //    if (musers != null && musers.Count > 0)
            //    {
            //        Maticsoft.Model.userdata data = musers[0];
            //        if (data.tj_id == 0)
            //        {
            //            return null;
            //        }

            //        TimeSpan ts1 = new TimeSpan(DateTime.Now.Ticks); //获取当前时间的刻度数 
            //        TimeSpan ts2 = new TimeSpan(Convert.ToDateTime(data.day).Ticks);  
            //        TimeSpan ts = ts2.Subtract(ts1).Duration(); //时间差的绝对值  
            //        if (ts.Hours <= 24) //少于24小时
            //        {
            //            Maticsoft.Model.userdata tjuser = buser.GetModel(data.tj_id);
            //            if (tjuser == null)
            //            {
            //                return null;
            //            }
            //            decimal tjmoney = Convert.ToDecimal(Maticsoft.Common.GlobalVar.Instance.GetAppConfig("reg_yzr1"));
            //            //如果推荐者的余额大于邀请奖励,则直接减去奖励金额
            //            if (tjuser.money >= tjmoney)
            //            {
            //                tjuser.money -= tjmoney;
            //                buser.Update(tjuser);
            //            }
            //            else
            //            {
            //                //推荐用户余额不足,则查看用户是否具有提现数据,如果用户具有申请的提现数据,则直接拒绝用户提现请求,并扣除推荐奖励
            //                Maticsoft.BLL.txdata btxdata = new Maticsoft.BLL.txdata();
            //                DataSet ds2 = btxdata.GetList(" uid='" + tjuser.id + "' and state != '2' and state != '1'");
                            
            //                if (!Maticsoft.Common.Util.CheckDataSet(ds2)) //没有提现数据,则直接将用户余额改成0
            //                {
            //                    tjuser.money = 0;
            //                    buser.Update(tjuser);
            //                }
            //                else {
            //                    decimal txsum = 0;
            //                    for (int i = 0; i < ds2.Tables[0].Rows.Count; i++)
            //                    {
            //                        txsum += Convert.ToDecimal(ds2.Tables[0].Rows[i]["money"].ToString());

            //                        int txid = Convert.ToInt32(ds2.Tables[0].Rows[i]["id"].ToString());
            //                        btxdata.Delete(txid);
            //                    }

            //                    txsum -= tjmoney;
            //                    tjuser.money += txsum;

            //                    buser.Update(tjuser);
            //                }
            //            }
            //        }
            //    }
            //}
            return null;
        }


        private Maticsoft.Model.tb_userdata AddUser(string fromusername)
        {
            Maticsoft.BLL.tb_userdata buser = new Maticsoft.BLL.tb_userdata();
           // List<Maticsoft.Model.tb_userdata> users = buser.GetModelList(" wxid = '" + fromusername + "' ");
            Maticsoft.Model.tb_userdata muser = new Maticsoft.Model.tb_userdata();
            //if (users == null || users.Count == 0)
            //{
                UserInfoJson ou = User.Info(WeixinConfig.TokenHelper.GetToken(true), fromusername);
                
                if (ou == null)
                {
                    muser.realname = "";
                    muser.imgurl = Maticsoft.Common.GlobalVar.Instance.AppDataQrDir + "gzh.png";
                }
                else
                {
                    muser.realname = ou.nickname;
                    muser.imgurl = ou.headimgurl;
                }

                //首次添加公众号
                muser.qrpath = "";
                muser.wxid = fromusername;
                muser.jifen = Convert.ToDecimal(Maticsoft.Common.Utils.GetAppSettingValue("gzjifen"));
                muser.freezejifen = 0;
                muser.tj_num = 0;
                muser.gz_time = DateTime.Now;
                muser.qrmediaid = " ";
                muser.qr_expire_date = DateTime.Now.AddDays(-1);
                buser.Add(muser);

                muser = GetUserByOpenId(fromusername);
            return muser;
        }

        private void CreateQr(string fromusername,bool force = false)
        {
            Maticsoft.BLL.tb_userdata buser = new Maticsoft.BLL.tb_userdata();
            List<Maticsoft.Model.tb_userdata> users = buser.GetModelList(" wxid = '" + fromusername + "' ");
            Maticsoft.Model.tb_userdata muser = null;
            if (users == null || users.Count == 0)
            {
                return;
            }
            muser = users[0];

            if (!string.IsNullOrWhiteSpace(muser.qrpath)) //未在本地生成图片
            {
                string qrmediaid = muser.qrmediaid;
                if (string.IsNullOrWhiteSpace(qrmediaid))
                {
                    StartThread(muser);
                    return;
                }
                else
                {
                    DateTime expiredate = muser.qr_expire_date;
                    if (force)
                    {
                        StartThread(muser);
                        return;
                    }
                    else
                    {
                        if (DateTime.Now > expiredate)
                        {//过期
                            UploadImage(muser);
                        }
                    }
                    SendQrImage(muser);
                }
            }
            else
            {
                StartThread(muser);
            }
        }

        private void StartThread(Maticsoft.Model.tb_userdata muser)
        {
            ParameterizedThreadStart ParStart = new ParameterizedThreadStart(ThreadMethod);
            Thread myThread = new Thread(ParStart);
            myThread.IsBackground = true;
            myThread.Start(muser);
        }

        private void UploadImage(Maticsoft.Model.tb_userdata muser)
        {
            using (FileStream fs = new FileStream(Maticsoft.Common.GlobalVar.Instance.AppRootDir + muser.qrpath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                string mediaid = MaterialAPI.UploadTempMedia(WeixinConfig.TokenHelper.GetToken(), "image", DateTime.Now.ToString("yyyyMMddhhmmssffff") + ".jpg", fs);
                muser.qrmediaid = mediaid;
                muser.qr_expire_date = DateTime.Now.AddDays(3);
                Maticsoft.BLL.tb_userdata buser = new Maticsoft.BLL.tb_userdata();
                buser.Update(muser);
            }
        }

        private void SendQrImage(Maticsoft.Model.tb_userdata muser)
        {
            if (!ReplayActiveMessageAPI.RepayImage(WeixinConfig.TokenHelper.GetToken(), muser.wxid, muser.qrmediaid))
            {
                AppCommon.Instance.LoggerHandler.Log("主动推送图片消息失败");
            }
        }

        public void ThreadMethod(object ParObject)
        {
            try
            {
                Maticsoft.Model.tb_userdata muser = (Maticsoft.Model.tb_userdata)ParObject;

                CreateQrCodeResult qrret = QrCode.Create(WeixinConfig.TokenHelper.GetToken(true), 0, muser.id);
                string mainpath = Maticsoft.Common.GlobalVar.Instance.AppDataQrDir;
                string userpath = mainpath + muser.id + "\\";
                if (!Directory.Exists(userpath))
                {
                    Directory.CreateDirectory(userpath);
                }
                string qrpath = userpath + muser.wxid.ToString() + ".png";
                using (FileStream fs = new FileStream(qrpath, FileMode.OpenOrCreate))
                {
                    QrCode.ShowQrCode(qrret.ticket, fs);
                    fs.Flush();
                }

                //缩小二维码
                string reduceqr = userpath + muser.wxid.ToString() + "_samll.png";
                reduceqr = ReduceImage(qrpath, reduceqr, 128, 128);

                string preheadimg = userpath + "head.png";
                preheadimg = userpath + "head.png";
                GetHeadImg(preheadimg, muser);
                //缩小头像
                string reduceheadimg = userpath + "small_" + muser.wxid + ".png";
                reduceheadimg = ReduceImage(preheadimg, reduceheadimg, 64, 64);

                //头像变成圆形
                string headimg = userpath + "cir_" + muser.wxid + ".png";
                processheadimg(reduceheadimg, headimg);

                string body_path = mainpath + "xk.jpg";

                GenerateImage.favoriteImage[] FaImage = new GenerateImage.favoriteImage[2];

                FaImage[0].x = 80;
                FaImage[0].y = 365;
                FaImage[0].imagePath = headimg;

                FaImage[1].x = 50;//65;
                FaImage[1].y = 445;
                FaImage[1].imagePath = reduceqr;

                string filename = generateWinterMark(userpath, body_path, FaImage);

                //filename = AddText(userpath,filename, new Point(127, 450), "我是" + muser.realname);
                //filename = AddText(userpath, filename, new Point(60, 600), string.Format("该二维码{0}日过期", DateTime.Now.AddDays(3).ToString("yyyy-MM-dd")));
                //filename = AddText(userpath, filename, new Point(20, 210), "长按识别图中的二维码,领取限时奖励");
                Maticsoft.BLL.tb_userdata buser = new Maticsoft.BLL.tb_userdata();
                muser.qrpath = filename.Substring(Maticsoft.Common.GlobalVar.Instance.AppRootDir.Length);
                buser.Update(muser);
                UploadImage(muser);

                SendQrImage(muser);
            }
            catch (System.Exception ex)
            {
                AppCommon.Instance.LoggerHandler.Log(ex.Message);
                AppCommon.Instance.LoggerHandler.Log(ex.StackTrace);
            }
        }

        /**/
        /// <summary>
        /// 生成水印
        /// </summary>
        /// <param name="Main">主图片路径,eg:body</param>
        /// <param name="Child">要叠加的图片路径</param>
        /// <param name="x">要叠加的图片位置的X坐标</param>
        /// <param name="y">要叠加的图片位置的Y坐标</param>
        /// <param name="isSave"></param>
        /// <returns>生成图片的路径</returns>        
        private string generateWinterMark(string savePath, string body_path, GenerateImage.favoriteImage[] favorite)
        {
            //create a image object containing the photograph to watermark
            System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(body_path);
            int phWidth = imgPhoto.Width;
            int phHeight = imgPhoto.Height;

            //create a Bitmap the Size of the original photograph
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

            //设置此 Bitmap 的分辨率。 
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //load the Bitmap into a Graphics object 
            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            //Set the rendering quality for this Graphics object
            grPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//清除锯齿的呈现
            //haix
            for (int i = 0; i < favorite.Length; i++)
            {
                //Draws the photo Image object at original size to the graphics object.
                grPhoto.DrawImage(
                    imgPhoto,                               // Photo Image object
                    new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
                    0,                                      // x-coordinate of the portion of the source image to draw. 
                    0,                                      // y-coordinate of the portion of the source image to draw. 
                    phWidth,                                // Width of the portion of the source image to draw. 
                    phHeight,                               // Height of the portion of the source image to draw. 
                    GraphicsUnit.Pixel);                    // Units of measure


                //------------------------------------------------------------
                //Step #2 - Insert Property image,For example:hair,skirt,shoes etc.
                //------------------------------------------------------------
                //create a image object containing the watermark
                System.Drawing.Image imgWatermark = new Bitmap(favorite[i].imagePath);
                int wmWidth = imgWatermark.Width;
                int wmHeight = imgWatermark.Height;


                //Create a Bitmap based on the previously modified photograph Bitmap
                Bitmap bmWatermark = new Bitmap(bmPhoto);
               // bmWatermark.MakeTransparent(); //使默认的透明颜色对此 Bitmap 透明。

                //bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
                //Load this Bitmap into a new Graphic Object
                Graphics grWatermark = Graphics.FromImage(bmWatermark);


                int xPosOfWm = favorite[i].x;
                int yPosOfWm = favorite[i].y;

                //叠加
                grWatermark.DrawImage(imgWatermark, new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight),  //Set the detination Position
                0,                  // x-coordinate of the portion of the source image to draw. 
                0,                  // y-coordinate of the portion of the source image to draw. 
                wmWidth,            // Watermark Width
                wmHeight,            // Watermark Height
                GraphicsUnit.Pixel, // Unit of measurment
                null);   //ImageAttributes Object


                //Replace the original photgraphs bitmap with the new Bitmap
                imgPhoto = bmWatermark;

                //grWatermark.Dispose();
                imgWatermark.Dispose();
                //grPhoto.Dispose();                
                //bmWatermark.Dispose();
            }
            //haix

            string nowTime = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();

            string saveImagePath = savePath + "\\" + nowTime + ".png";

            if (File.Exists(saveImagePath))
            {
                File.Delete(saveImagePath);
            }
            //save new image to file system.
            imgPhoto.Save(saveImagePath, ImageFormat.Png);



            imgPhoto.Dispose();

            bmPhoto.Dispose();
            return saveImagePath;
        }

        private void processheadimg(string filepath,string newfile)
        {
            System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(filepath);
            System.Drawing.Image newimg = CutEllipse(imgPhoto, new Rectangle(0, 0, 64, 64), new Size(64, 64));
            newimg.Save(newfile, ImageFormat.Png);
            imgPhoto.Dispose();
            newimg.Dispose();
        }

        private System.Drawing.Image CutEllipse(System.Drawing.Image img, Rectangle rec, Size size)
        {
            Bitmap bitmap = new Bitmap(size.Width, size.Height);
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                using (TextureBrush br = new TextureBrush(img, System.Drawing.Drawing2D.WrapMode.Clamp, rec))
                {
                    br.ScaleTransform(bitmap.Width / (float)rec.Width, bitmap.Height / (float)rec.Height);
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.FillEllipse(br, new Rectangle(Point.Empty, size));
                }
            }
            return bitmap;
        }

        public string ReduceImage(string srcfile,string tofile, int toWidth = 128, int toHeight= 128)
        {
            System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(srcfile);
            if (toWidth <= 0 && toHeight <= 0)
            {
                return srcfile;
            }
            else if (toWidth > 0 && toHeight > 0)
            {
                if (imgPhoto.Width < toWidth && imgPhoto.Height < toHeight)
                    return srcfile;
            }
            else if (toWidth <= 0 && toHeight > 0)
            {
                if (imgPhoto.Height < toHeight)
                    return srcfile;
                toWidth = imgPhoto.Width * toHeight / imgPhoto.Height;
            }
            else if (toHeight <= 0 && toWidth > 0)
            {
                if (imgPhoto.Width < toWidth)
                    return srcfile;
                toHeight = imgPhoto.Height * toWidth / imgPhoto.Width;
            }
            System.Drawing.Image toBitmap = new Bitmap(toWidth, toHeight);

            using (Graphics g = Graphics.FromImage(toBitmap))
            {
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.Clear(Color.Transparent);
                g.DrawImage(imgPhoto,
                            new Rectangle(0, 0, toWidth, toHeight),
                            new Rectangle(0, 0, imgPhoto.Width, imgPhoto.Height),
                            GraphicsUnit.Pixel);
            }
            toBitmap.Save(tofile, ImageFormat.Png);
            imgPhoto.Dispose();
            toBitmap.Dispose();
            return tofile;
        }

        private string AddText(string userpath,string filename, Point pt, string content)
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile(filename);
            Bitmap bmp = new Bitmap(img);
            Graphics g = Graphics.FromImage(bmp);
            string newfile = userpath + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss_FFF") + ".png";
            Font font = new Font("宋体", 14);
            SolidBrush sbrush = new SolidBrush(Color.White);
            g.DrawString(content, font, sbrush, pt);
            bmp.Save(newfile, System.Drawing.Imaging.ImageFormat.Png);
            img.Dispose();
            bmp.Dispose();
            File.Delete(filename);
            return newfile;
        }

        private void GetHeadImg(string filepath,Maticsoft.Model.tb_userdata muser)
        {
            string url = muser.imgurl;
            if (string.IsNullOrEmpty(url))
            {
                filepath = Maticsoft.Common.GlobalVar.Instance.AppDataQrDir + "wx.jpg";
                return;
            }
            System.Net.WebClient mywebclient = new System.Net.WebClient();
            mywebclient.DownloadFile(url, filepath);
        }
    }

    public class GenerateImage
    {
        public struct favoriteImage
        {
            private string _imagePath;
            private int _x;
            private int _y;

            public int x
            {
                get
                {
                    return _x;
                }
                set
                {
                    _x = value;
                }
            }

            public int y
            {
                get
                {
                    return _y;
                }
                set
                {
                    _y = value;
                }
            }

            public string imagePath
            {
                get
                {
                    return _imagePath;
                }
                set
                {
                    _imagePath = value;
                }
            }
        }
    }
}